package com.lenovo.lcdm.dcm.common.version;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Api version condition
 *
 * @author zhangcheng26
 */
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {
    //  /v[1-9]/
    private static final Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(\\d+)");
    private int apiVersion;

    ApiVersionCondition(int apiVersion) {
        this.apiVersion = apiVersion;
    }

    @NotNull
    @Override
    public ApiVersionCondition combine(@NotNull ApiVersionCondition other) {
        return new ApiVersionCondition(other.getApiVersion());
    }

    @Override
    public ApiVersionCondition getMatchingCondition(@NotNull HttpServletRequest request) {
        String versionStr = request.getRequestURI().split("/")[2];
        Matcher m = VERSION_PREFIX_PATTERN.matcher(versionStr);
        if (m.matches()) {
            Integer version = Integer.valueOf(m.group(1));
            if (version >= this.apiVersion) {
                return this;
            }
        } else {
            return this;
        }
        return null;
    }

    @Override
    public int compareTo(@NotNull ApiVersionCondition other, @NotNull HttpServletRequest request) {
        return other.getApiVersion() - this.apiVersion;
    }

    private int getApiVersion() {
        return apiVersion;
    }
}
